<?php
namespace app\common\repositories\apps;


use app\common\repositories\BaseRepository;
use app\common\dao\apps\AppsDao;
use app\common\model\apps\AppsModel;
use app\common\service\MembershipService;
use support\Container;
use think\facade\Db;

class AppsRepository extends BaseRepository
{
    public $limit = 10;
    protected $dao;
    public function __construct(){
        $this->dao = new AppsDao();
    }

    /**
     * @desc: get list
     * @author: generate
     * @param {*} $where
     * @param {*} $page
     * @param {*} $limit
     */
    public function getList($where = [],$page = 1,$limit = 100) {

        $order = 'id DESC';
        $query = $this->dao->search($where)->orderRaw($order);
        $count = $query->count();

        // echo AppsModel::getLastSql();

        $list =  $query->page($page, $limit)->select()->each(function($item) {
            $item = $this->formateItemRow($item);
        });
        // echo AppsModel::getLastSql();

        return compact('count','list');
    }
    /**
     * @desc: formate item row
     * @author: generate
     * @param {*} $item
     */
    public function formateItemRow($item){
        if(empty($item)) return [];
        return $item;
    }


    /**
     * @desc: formate item row detial
     * @author: generate
     * @param {*} $item
     */    
    public function formateItemRowDetail($item){
        if(empty($item)) return [];
        $item = $this->formateItemRow($item);

        $stores = [];
        if($item->is_huawei > 0){
            $stores[] = 'huawei';
        }
        if($item->is_xiaomi > 0){
            $stores[] = 'xiaomi';
        }
        if($item->is_vivo > 0){
            $stores[] = 'vivo';
        }
        if($item->is_oppo > 0){
            $stores[] = 'oppo';
        }
        if($item->is_honour > 0){
            $stores[] = 'honour';
        }
        if($item->is_yyb > 0){
            $stores[] = 'yyb';
        }

        $item->stores = $stores;
        return $item;
    }

    /**
     * @desc: generate appkey
     * @author: xiaohp
     * @param {*} $length
     */
    public function generateAppKey($length = 32) {
        return bin2hex(random_bytes($length / 2));
    }

    /**
     * @desc: create one Apps
     * @param varchar $name               
     * @param varchar $appkey             
     * @param varchar $android_scheme_url 
     * @param varchar $ios_scheme_url     
     * @param varchar $universal_links    
     * @param varchar $package_name       
     * @param tinyint $is_huawei          
     * @param tinyint $is_xiaomi          
     * @param tinyint $is_vivo            
     * @param tinyint $is_oppo            
     * @param tinyint $is_honour          
     * @param tinyint $is_yyb             
     * @param varchar $icon               
     * @param varchar $banner             
     * @param int     $user_id            
     * @author: generate
     */
    public function createOneApps(
        $name = '',
        $android_scheme_url = '',
        $ios_scheme_url = '',
        $universal_links = '',
        $package_name = '',
        $is_huawei = 0,
        $is_xiaomi = 0,
        $is_vivo = 0,
        $is_oppo = 0,
        $is_honour = 0,
        $is_yyb = 0,
        $icon = '',
        $banner = '',
        $user_id = 0,
        $stores = [],
        $huawei_down_url = '',
        $xiaomi_down_url = '',
        $vivo_down_url = '',
        $oppo_down_url = '',
        $honour_down_url = '',
        $yyb_down_url = ''
    ) {
        // 检查会员权限
        $permissionCheck = MembershipService::canCreateApp($user_id);
        if (!$permissionCheck['can_create']) {
            return ['code' => 0, 'msg' => $permissionCheck['reason']];
        }

        // 记录用户操作日志
        MembershipService::logUserAction($user_id, 'app_create_attempt', 'app', null, null, ['name' => $name]);


        $appkey = $this->generateAppKey(32);
        
        $is_huawei = in_array('huawei', $stores) ? 1: 0 ;
        $is_xiaomi = in_array('xiaomi', $stores) ? 1: 0 ;
        $is_vivo = in_array('vivo', $stores) ? 1: 0 ;
        $is_oppo = in_array('oppo', $stores) ? 1: 0 ;
        $is_honour = in_array('honour', $stores) ? 1: 0 ;
        $is_yyb = in_array('yyb', $stores) ? 1: 0 ;
        
        // to do  some check
        $data = compact('name','appkey','android_scheme_url','ios_scheme_url','universal_links','package_name','is_huawei','is_xiaomi','is_vivo','is_oppo','is_honour','is_yyb','icon','banner','user_id','huawei_down_url','xiaomi_down_url','vivo_down_url','oppo_down_url','honour_down_url','yyb_down_url');

        $data['is_del'] = 0;
        $data['status'] = 1;
        $data['create_at'] =  date('Y-m-d H:i:s');

        $id = Db::transaction(function () use($data) {
            $id = $this->create($data);
            // todo other
            return $id;
        });

        // 记录成功的应用创建操作
        MembershipService::logUserAction($user_id, 'app_create_success', 'app', $id, null, $data);

        return ['code' => 200, 'msg' => 'ok', 'data' => ['id' => $id]];
    }

    /**
     * @desc: update one Apps
     * param int  id
     * @param varchar $name               
     * @param varchar $appkey             
     * @param varchar $android_scheme_url 
     * @param varchar $ios_scheme_url     
     * @param varchar $universal_links    
     * @param varchar $package_name       
     * @param tinyint $is_huawei          
     * @param tinyint $is_xiaomi          
     * @param tinyint $is_vivo            
     * @param tinyint $is_oppo            
     * @param tinyint $is_honour          
     * @param tinyint $is_yyb             
     * @param varchar $icon               
     * @param varchar $banner             
     * @param int     $user_id            
     * @author: generate
     */
    public function updateOneApps(
        $id,
        $name = '',
        $android_scheme_url = '',
        $ios_scheme_url = '',
        $universal_links = '',
        $package_name = '',
        $is_huawei = 0,
        $is_xiaomi = 0,
        $is_vivo = 0,
        $is_oppo = 0,
        $is_honour = 0,
        $is_yyb = 0,
        $icon = '',
        $banner = '',
        $user_id = 0,
        $stores = [],
        $huawei_down_url = '',
        $xiaomi_down_url = '',
        $vivo_down_url = '',
        $oppo_down_url = '',
        $honour_down_url = '',
        $yyb_down_url = ''
    ) {

        if(empty($id)) return ['code'=>0,'msg'=>'请选择操作的项'];
        if($this->exists($id) == false) return ['code'=>0,'msg'=>'操作的项不存在'];

        $is_huawei = in_array('huawei', $stores) ? 1: 0 ;
        $is_xiaomi = in_array('xiaomi', $stores) ? 1: 0 ;
        $is_vivo = in_array('vivo', $stores) ? 1: 0 ;
        $is_oppo = in_array('oppo', $stores) ? 1: 0 ;
        $is_honour = in_array('honour', $stores) ? 1: 0 ;
        $is_yyb = in_array('yyb', $stores) ? 1: 0 ;


        // to do  some check

        $update = compact('name','android_scheme_url','ios_scheme_url','universal_links','package_name','is_huawei','is_xiaomi','is_vivo','is_oppo','is_honour','is_yyb','icon','banner','user_id','huawei_down_url','xiaomi_down_url','vivo_down_url','oppo_down_url','honour_down_url','yyb_down_url');
        $update['update_at'] =  date('Y-m-d H:i:s');

        $res = Db::transaction(function () use($id,$update) {
            $res = $this->update($id,$update);
            // todo other

            return $res;
        });
        return ['code' => 200, 'msg' => 'ok', 'data' => ['id' => $id,'res' => $res]];
    }


    /**
     * @desc: del one Apps
     * @author: generate
     * @param {*} $id
     */
    public function delOneApps($id) {
        if(empty($id)) return ['code' => 0, 'msg' => '请选择操作的项', 'data' => []];
        if(!$this->exists($id)) return ['code' => 0, 'msg' => '操作的项不存在', 'data' => []];

        $update = ['is_del' => 1,'update_at' => date('Y-m-d H:i:s')];
        $res = $this->update($id,$update);

        // important 如果是关联其他的 必须使用事务包裹删除 具体参考修改

        return ['code' => 200, 'msg' => 'ok', 'data' => ['id' => $id,'res' => $res]];
    }

    /**
     * @desc: getDetail
     * @author: generate
     */
    public function getDetail($id){
        $info = $this->dao->search(['id' => $id])->find();
        if (empty($info)){
            return [];
        }
        $info = $this->formateItemRowDetail($info);
        return $info;
    }
    /**
     * @desc: get statistic
     * @author: xiaohp
     * @param {*} $id
     */
    public function statistics($id){
        $detail = $this->getDetail($id);
        $app_key = $detail->app_key ?? '';

        // 落地页数据
        $web = Container::make(AppsWebRepository::class)->getAppStatistics($app_key);


        // app页数据
        $app = Container::make(AppsAppsRepository::class)->getAppStatistics($app_key);


        $line = Container::make(AppsWebRepository::class)->getAppStatisticsLine($app_key);
        return ['web' => $web, 'app' => $app,'line' => $line];
    }


    /**
     * @desc: get one apps by app_key
     * @author: xiaohp
     * @param {*} $token
     */
    public function getOneAppInfoByAppkey($app_key){
        $user = $this->dao->search(['appkey_key' => $app_key,'status' => 1,'is_del' =>0])->find();
        return $user;
    }
}